import datetime
import logging
import os
import shutil
import tempfile
import urllib2

_LOGGER = logging.getLogger(__name__)

def tupleize(value, keep_none=False):
	"""Transform a original value into a tuple"""
	if value is None and not keep_none:
		return ()
	if type(value) in (tuple, list):
		return tuple(value)
	return (value,)


def need_download(url, local_file):
	if not os.path.exists(local_file):
		return True
	try:
		infos = urllib2.urlopen(url).info()
		url_timetuple = infos.getdate("last-modified") or infos.getdate("date")
		url_date = datetime.datetime.now()
		if url_timetuple:
			url_date = datetime.datetime(*url_timetuple[:6])
		local_file_date = datetime.datetime.fromtimestamp(os.path.getmtime(local_file))
		_LOGGER.debug("Distant file as date %s, local file as date %s, need to download : %s",
			url_date, local_file_date, local_file_date < url_date)
		return local_file_date < url_date
	except:
		_LOGGER.exception("Error when checking download info on url (%s)", url)
		return True

def download_image(url, filepath):
	if not os.path.isdir(os.path.dirname(filepath)):
		os.makedirs(os.path.dirname(filepath))
	if need_download(url, filepath):
		fd = file(filepath, "wb+")
		try:
			fd.write(urllib2.urlopen(url).read())
		finally:
			fd.close()


class MovieLibraryBuilder(object):
	def __init__(self):
		self.base_dir = tempfile.mkdtemp()
		self.files = {}

	def join(self, *pathparts):
		return os.path.join(self.base_dir, *pathparts)

	def clean(self):
		shutil.rmtree(self.base_dir)

	def create_file(self, path):
		filepath = self.join(path)
		dir = os.path.dirname(filepath)
		if not os.path.isdir(dir):
			os.makedirs(dir)
		fd = file(filepath, "w")
		fd.close()
		return filepath

	def build_flat_library(self, *movies):
		for movie in movies:
			self.files[movie] = self.create_file(movie)

	def build_subdir_arch_library(self, *movies):
		for movie in movies:
			self.files[movie] = self.create_file("%s/%s" % (os.path.basename(movie), movie))


